/**
 * About News search, add, delete and so on.
 */

const db = require('../../config/db')
const axios = require('axios')
const cheerio = require('cheerio')

/**
 * addNews
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addNews = async(req, res) => {
    try {
        const {college, sport, mainTitle, subTitle, url, content, pubStatus} = req.body
        if(url != "") {
            const contentHtml = await getWeChatContent(url)
            // await getWeChatMeta(url)
            // console.log("contentHtml: ", contentHtml)
            // content = contentHtml
        }
        if(college == "")
            return res.status(201).json({error: "需要选择学院!"})
        if(sport == "")
            return res.status(201).json({error: "需要选择运动!"})
        if(mainTitle == "")
            return res.status(201).json({error: "主标题不能为空!"})
        if(content == "")
            return res.status(201).json({error: "内容不能为空!"})
        const sql = `INSERT INTO news
                    (main_title, sub_title, content, time, pub_status)
                    values
                    (?, ?, ?, NOW(), ?)`
        const [rows] = await db.query(sql, [mainTitle, subTitle, content, pubStatus])

        if(rows.affectedRows == 0) {
            return res.status(201).json({error: "添加失败!"})
        }
        const insertId1 = rows.insertId
        // 存入学院运动资讯关联表
        const sql2 =  `INSERT INTO college_sport_news
                       (college, sport, news_id)
                       values
                       (?, ?, ?)`
        const [row2] = await db.query(sql2, [college, sport, insertId1])
        if(row2.affectedRows == 0) {
            return res.status(201).json({error: "添加失败!"})
        }
        console.log("添加资讯成功!")
        res.status(200).json({success: "添加资讯成功!"})
    } catch(err) {
        console.log("error: ", err)
        res.status(500).json({error: "服务器异常，请稍后重试!"})
    }
    
}

/**
 * deleteNews
 */
exports.deleteNewById = async(req, res) => {
    try {
        const {newsId} = req.body
        const sql = `DELETE FROM news
                     where news_id = ?`
        const sql2= `DELETE FROM college_sport_news
                     where news_id = ?`            
        const [rows] = await db.query(sql, [newsId])
        const [rows2] = await db.query(sql2, [newsId])
        if(rows.affectedRows == 0 || rows2.affectedRows == 0) {
            return res.status(201).json({error: "删除失败!"})
        }
        res.status(200).json({success: "删除成功!"})
    } catch(err) {
        res.status(500).json({error: "服务器异常, 请稍后重试"})
    }
}

/**
 * Publish News
 */
exports.updateNewsStatus = async(req, res) => {
    try {
        const {newsId, pubStatus} = req.body
        const sql = `UPDATE news
                     SET pub_status = ?
                     where news_id = ?
                     `
        const [rows] = await db.query(sql, [pubStatus, newsId])
        if(rows.affectedRows == 0) {
            returnres.status(201).json({error: "更新资讯失败!"})
        }
        res.status(200).json({success: "更新资讯成功!"})
    } catch(err) {
        console.log("error:", err)
        return res.status(500).json({error: "服务器异常，请稍后重试!"})
    }
}

async function getWeChatContent(url) {
  try {
    const { data } = await axios.get(url, {
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        "Referer": "https://mp.weixin.qq.com/",
      },
    });

    const $ = cheerio.load(data);
    const richTitle = $("#activity-name").text().trim(); // 获取内容
    const authorName = $("#js_name").text().trim(); // 获取作者名称
    const pubTime = $("#meta_content_hide_info").text().trim(); // 获取发布时间
    const ipAddr = $("#js_ip_wording_wrp").text().trim(); // 获取发布地址
    
    const contentHtml = $("#js_content").html(); // 获取正文

    
    console.log("richTitle:", richTitle ? "获取成功" : "为空");
    console.log("richTitle:", richTitle);
    console.log("authorName:", authorName);
    console.log("pubTime:", pubTime);
    console.log("ipAddr:", ipAddr);
    console.log("contentHtml:", contentHtml ? "获取成功" : "为空");
    return contentHtml;
  } catch (err) {
    console.error("获取微信文章失败:", err);
    return null;
  }
}

async function getWeChatMeta(url) {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();

  await page.goto(url, { waitUntil: "networkidle2" });

  // 获取发布时间
  const pubTime = await page.$eval("#publish_time", el => el.textContent.trim());

  // 获取发布地区
  const ipAddr = await page.$eval("#js_ip_wording", el => el.textContent.trim());

  await browser.close();

  console.log("发布时间:", pubTime);
  console.log("发布地区:", ipAddr);
  return { pubTime, ipAddr };
}
